'''
Created on 12.09.2009

@author: ankstoo
'''

from pygs.services.security.encoder import encoderInstance
from pygs.services.security.securityPersistence import SecurityPersistence


class SecurityPersistenceInMemory(SecurityPersistence):
    '''
    '''

    users = {"user1Id": {"userName": "user1", "userId": "user1Id", "passwd": encoderInstance.encodeSHA1("11111")},
             "user2Id": {"userName": "user2", "userId": "user2Id", "passwd": encoderInstance.encodeSHA1("qwerty")}}
    
    def __init__(self):
        SecurityPersistence.__init__(self)
        self.tokens = {}
    
    def saveToken(self, token, tokenData):
        self.tokens[token] = tokenData
    
    def loadTokenData(self, token):
        if not token in self.tokens:
            return None
        return self.tokens[token]
    
    def deleteToken(self, token):
        if token in self.tokens:
            del self.tokens[token]
            return True
        else:
            return False   
        
    def getUserParams(self, userId, paramNames):
        if not self.users.has_key(userId):
            return None
        result = {}
        for name in paramNames:
            if self.users[userId].has_key(name):
                result[name] = self.users[userId][name]
        return result
    
    def findUserByName(self, userName):
        for user in self.users.itervalues():
            if user["userName"] == userName:
                return user["userId"]
        return None
    
    def getUserParamsByUserName(self, userName, paramNames):
        userId = self.findUserByName(userName)
        if not userId:
            return None
        else:
            return self.getUserParams(userId, paramNames)       